package com.example.notes;



import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import interfaces.Noteable;
import interfaces.NoteableAdapter;
import notes.NoteWithPicture;
import notes.NotesDatabase;
import android.os.Bundle;


import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Point;
import android.view.View.OnClickListener;
import android.view.Gravity;

import android.view.Display;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.Toast;

import android.widget.TextView;

import android.widget.LinearLayout;
import android.widget.TableLayout;


public class MainActivity extends Activity implements OnClickListener {
	private boolean[] itemsChecked;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_main);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		
		loadNotes();
		
		addNotes();
		addButtons();	

	}

	private void loadNotes() {
		SharedPreferences prefs = getPreferences(MODE_PRIVATE);
		Noteable[] allNotes = new Noteable[prefs.getInt("NoteLength", 0)];
		Gson gson = null;
		GsonBuilder builder = new GsonBuilder();
        builder.registerTypeAdapter(Noteable.class, new NoteableAdapter());
        gson = builder.create();
		String json = "";
		
		for(int i = 0; i < allNotes.length; i++) {
			json = prefs.getString("Note" + i, "");
			allNotes[i] = gson.fromJson(json, Noteable.class);
		}
		NotesDatabase.loadArray(allNotes);
	}
	

	private void saveNotes() {
		Noteable[] allNotes = new Noteable[NotesDatabase.getNotesCount()];
		SharedPreferences prefs = getPreferences(MODE_PRIVATE);
		Editor prefsEditor = prefs.edit();
		Gson gson = null;
		GsonBuilder builder = new GsonBuilder();
        builder.registerTypeAdapter(Noteable.class, new NoteableAdapter());
        gson = builder.create();
		String json = "";
		prefsEditor.putInt("NoteLength", allNotes.length);
		if (NotesDatabase.getNotesCount() >= 1 && NotesDatabase.saveArray(allNotes)) {
			for(int i = 0; i < allNotes.length; i++) {
				json = gson.toJson(allNotes[i], Noteable.class);
				prefsEditor.putString("Note" + i, json);
			}
		}
		prefsEditor.commit();
	}

	private void addButtons() {
		Button addNote = (Button) findViewById(R.id.addNote);
		Button deleteButton = (Button) findViewById(R.id.deleteNote);
		Button editNote = (Button) findViewById(R.id.editNote);
		Button emailNote = (Button) findViewById(R.id.emailNote);
		emailNote.setOnClickListener(this);
		addNote.setOnClickListener(this);	
		editNote.setOnClickListener(this);
		deleteButton.setOnClickListener(this);
	}

	private void addNotes() {
		int notesCount = NotesDatabase.getNotesCount();
		itemsChecked = new boolean[notesCount];
		TableLayout noteContainer = (TableLayout) findViewById(R.id.noteContainer);

		noteContainer.removeAllViewsInLayout();
		
		for (int i = 0; i < notesCount; i++) {
			LinearLayout newRow = new LinearLayout(this);
			newRow.setOrientation(LinearLayout.HORIZONTAL);

			Noteable currentNote = NotesDatabase.getNote(i);
			
			CheckBox buyCheck = new CheckBox(this);
			buyCheck.setPadding(5, 5, 5, 5);
			buyCheck.setGravity(Gravity.LEFT);
			buyCheck.setId(i);
			final int place = i;
			buyCheck.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
				
				@Override
				public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
					if (isChecked) {
							itemsChecked[place] = true;
					}
					else {
						itemsChecked[place] = false;
					}
					
				}
			});
			newRow.addView(buyCheck);

			// setting image
			if (currentNote instanceof NoteWithPicture) {
				setImage(newRow, currentNote);
			}
			// setting image

			setEnteredTitle(newRow, currentNote);
			
			
			setInputedTitle(noteContainer, newRow, currentNote);

		}
	}

	private void setInputedTitle(TableLayout noteContainer,
			LinearLayout newRow, Noteable currentNote) {
		final String timeString = currentNote.getTime();
		TextView time = new TextView(this);
		time.setTextColor(Color.WHITE);
		time.setPadding(80, 0, 0, 0);
		time.setGravity(Gravity.RIGHT);
		time.setText(timeString);
		time.setTextAppearance(this, android.R.style.TextAppearance_DeviceDefault_Large);
		
		noteContainer.addView(newRow);
	}

	private void setEnteredTitle(LinearLayout newRow, Noteable currentNote) {
		final String title = currentNote.getTitle();
		TextView titleOfNote = new TextView(this);
		titleOfNote.setTextColor(Color.WHITE);
		titleOfNote.setGravity(Gravity.LEFT);
		titleOfNote.setText(title);
		titleOfNote.setTextAppearance(this, android.R.style.TextAppearance_DeviceDefault_Large);
		newRow.addView(titleOfNote);
	}

	private void setImage(LinearLayout newRow, Noteable currentNote) {
		Bitmap image = BitmapFactory
				.decodeFile(((NoteWithPicture) currentNote)
						.getPicturePath());
		
		int height = getScreenHeight()/15;
		image = Bitmap.createScaledBitmap(image, height, height, true); // we want it to be a square picture
		
		ImageView iv = new ImageView(this);
		iv.setImageBitmap(image);
		
		newRow.addView(iv);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public void onClick(View v) {
		if(v.getId() == R.id.addNote) {
			Intent intent = new Intent(MainActivity.this, AddNoteActivity.class);
			startActivity(intent);
		}
		else if (v.getId() == R.id.editNote) {
			editNote();
		}
		else if(v.getId() == R.id.deleteNote) {
			deleteNoteDialog();
			
		}
		else if(v.getId() == R.id.emailNote) {
			emailNote();
		}
		else {
			//do nothing
		}
		

	}

	private void emailNote() {
		int checkedBoxes = 0;
		int lastCheckedBox = 0;
		for (int i = 0; i < NotesDatabase.getNotesCount(); i++) {
			if (itemsChecked[i]) {
				checkedBoxes++;
				lastCheckedBox = i;
			}
		}
		
		if(checkedBoxes == 1) {
			Intent intent = new Intent(MainActivity.this, SendMailActivity.class);
			intent.putExtra("CheckedIndex", lastCheckedBox);
			startActivity(intent);
		}
		else {
			Toast toast = Toast.makeText(MainActivity.this, "You can send only one note!", Toast.LENGTH_SHORT);
			toast.setGravity(Gravity.CENTER, 0, 0);
			toast.show();
		}
	}

	private void editNote() {
		int checkedBoxes = 0;
		int lastCheckedBox = 0;
		for (int i = 0; i < NotesDatabase.getNotesCount(); i++) {
			if (itemsChecked[i]) {
				checkedBoxes++;
				lastCheckedBox = i;
			}
		}
		
		if(checkedBoxes == 1) {
			Intent intent = new Intent(MainActivity.this, EditNoteActivity.class);
			intent.putExtra("CheckedIndex", lastCheckedBox);
			startActivity(intent);
		}
		else {
			Toast toast = Toast.makeText(MainActivity.this, "You can edit only one note!", Toast.LENGTH_SHORT);
			toast.setGravity(Gravity.CENTER, 0, 0);
			toast.show();
		}
	}

	private void deleteNoteDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
		builder.setMessage("Are you sure you want to delete this note?");
		builder.setTitle("Delete Note");
		builder.setCancelable(true);
		builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				for(int i = NotesDatabase.getNotesCount() - 1; i >= 0; i--) {
					if(itemsChecked[i]) {
						NotesDatabase.removeNote(i);
					}
				}
				addNotes();
			}
		});
		
		builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();
			}
		});
		
		AlertDialog alert = builder.create();
		alert.show();
	}
	
	@Override
	protected void onDestroy() {
		
		saveNotes();
		finish();
		super.onDestroy();
	}

	@Override
	protected void onResume() {
		super.onResume();
		addNotes();
	}
	
	@Override
	protected void onPause() {
		super.onPause();
//		saveNotes();
	}
	
	/**
	 * returns the width - height of the current phone screen
	 * @return - {width, height}
	 */
	private int getScreenHeight() {
		Display display = getWindowManager().getDefaultDisplay();
		Point size = new Point();
		display.getSize(size);

		return size.y;
	}
	
}
